package com.woyao;

import android.app.Application;
import android.app.ProgressDialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.ContactSummary;
import com.woyao.core.model.DemandSummary;
import com.woyao.core.model.GetMyDemandResponse;
import com.woyao.core.model.GetMyInterestResponse;
import com.woyao.core.model.InterestSummary;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.MediaSummary;
import com.woyao.core.model.ProfileResponse;
import com.woyao.core.model.User;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static android.content.Context.MODE_PRIVATE;
import static com.woyao.WoyaoooApplication.userId;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link InterestFragment.OnInterestFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link InterestFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class InterestFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public UserViewModel uvm;

    FrameLayout emptyArea;

    private Boolean personalAsked = false;
    private Boolean demandAsked = false;

    private LinearLayout theList;
    private com.woyao.InterestScrollview contentArea;

    private  boolean nomore = false;
    ContentResolver cr;

    List<InterestSummary> myInterests = new ArrayList<InterestSummary>();

    android.support.design.widget.FloatingActionButton addUpdate;

    FrameLayout theview;
    Toolbar toolbar;
    private Integer COMPLETE_ACCOUNT_CODE = 10;
    private Integer COMPLETE_CATEGORY_CODE = 55;   //
    private Integer ADD_UPDATE_CODE = 3000;
    private Integer ADD_DEMAND_CODE = 2000;
    private Integer MYREGISTER_CODE = 600;
    String  PERSUASION = "与朋友分享业务动态，请授权访问通信录";
    ProgressDialog progressDialog;
    private  Boolean contactAsked = false;
    private Boolean loading = false;
    private TextView toploading ;
    private TextView bottomloading ;



    private OnInterestFragmentInteractionListener mListener;
    private static final int ASKCONTACTS_CODE = 2;

    public InterestFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MessageFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static InterestFragment newInstance(String param1, String param2) {
        InterestFragment fragment = new InterestFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }



    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        theview = (FrameLayout) inflater.inflate(R.layout.fragment_interest, container, false);

        toolbar = (Toolbar) theview.findViewById(R.id.toolBar);
////        toolbar.setLogo(R.drawable.ic_launcher);
        toolbar.setTitle("动态");
        toolbar.inflateMenu(R.menu.chance);

        Menu menu = toolbar.getMenu();
        if (menu != null) {
            try {
                //如果不为空,就反射拿到menu的setOptionalIconsVisible方法
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                //暴力访问该方法
                method.setAccessible(true);
                //调用该方法显示icon
                method.invoke(menu, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.nav_search) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), SearchActivity.class);
                    startActivity(intent);
                }
                if (item.getItemId() == R.id.nav_change_category) {
                    if (!WoyaoooApplication.hasLogin) {
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent, MYREGISTER_CODE);
                        return false;
                    }
                    modifyCategory();
                }



                if (item.getItemId() == R.id.nav_publish_demand) {
                    if (!WoyaoooApplication.hasLogin){
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent,MYREGISTER_CODE);
                        return false;
                    }
//                    if (uvm.getUser().getDemand_id() == 0 ){
                        AddDemand();
//                    }else {
//                        Intent intent = new Intent();
//                        intent.putExtra("id", 0);
//                        intent.putExtra("category", "other");
//                        intent.setClass(getContext(), MoveActivity.class);
//                        startActivityForResult(intent, ADD_UPDATE_CODE);
//                    }
                }


//                if (item.getItemId() == R.id.nav_add_user) {
//                    Intent intent = new Intent();
//                    intent.setClass(getContext(), InviteActivity.class);
//                    startActivity(intent);
//                }

                if (item.getItemId() == R.id.nav_add_partner) {
                  if (!WoyaoooApplication.hasLogin){
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent,MYREGISTER_CODE);
                        return false;
                    }
//                    mListener.onTabChance(R.id.cooperate);
                    Intent intent = new Intent();
                    intent.setClass(getContext(), RelationActivity.class);
                    intent.putExtra("is_new",true);
                    startActivity(intent);
                }
                return false;
            }
        });
        emptyArea = (FrameLayout) theview.findViewById(R.id.empty_area);
        contentArea = (com.woyao.InterestScrollview) theview.findViewById(R.id.content_area);

        toploading = (TextView) theview.findViewById(R.id.interest_top_loading);
        bottomloading = (TextView) theview.findViewById(R.id.interest_bottom_loading);

        theList  = (LinearLayout) theview.findViewById(R.id.interest_items);

        contentArea.setChangedHandler(new InterestScrollview.Changed() {
            @Override
            public void Changed(String state) {

                if (state.equals("bottom")){
                    loadData(myInterests.size());
                }

                if (state.equals("top")){
                    loadData(0);
                }
            }
        });

        addUpdate = (android.support.design.widget.FloatingActionButton) theview.findViewById(R.id.update_add);
        addUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            if (!WoyaoooApplication.hasLogin){
                Intent intent = new Intent();
                intent.setClass(getContext(), RegisterActivity.class);
                startActivityForResult(intent,MYREGISTER_CODE);
                return ;
            }

            publishUpdate();


            }
        });


        loadData(0);


        return theview;
    }

    private void publishUpdate( ){


        AsyncTask<Void, Void, GetMyDemandResponse> task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
            @Override
            protected GetMyDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(WoyaoooApplication.userId, "false");
                try {
                    GetMyDemandResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyDemandResponse response) {

                final List<DemandSummary> demands = response.getContent();

                if (demands.size() ==0 ){
                    new AlertDialog.Builder(getContext())
                            .setTitle("信息")
                            .setMessage("请说明业务后，再发布动态。")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    AddDemand();
                                }
                            }).create().show();
                    return;
                }else{
                    Intent intent = new Intent();
                    intent.putExtra("id",0);
                    intent.putExtra("category","other");
                    intent.setClass(getContext(), MoveActivity.class);

                    startActivityForResult(intent, ADD_UPDATE_CODE);
                }

            }
            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void)null);

    }
    private Integer addUpdateChoice= 0;
    private void confirmPublishChoice( ){
        ArrayList<String> list = new ArrayList<String>();


        list.add( "发布动态");
        list.add( "发布业务");

        String[] items =  (String[])list.toArray(new String[0]);

        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(getContext());
        singleChoiceDialog.setTitle("发布业务信息");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        addUpdateChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String category = "";
                        if (addUpdateChoice == 3) {
                            AddDemand();
                            return;
                        }else if (addUpdateChoice == 0) {
                            category = "resource";
                        }else if (addUpdateChoice == 1) {
                            category = "demand";
                        }else if (addUpdateChoice == 2) {
                            category = "other";
                        }
                        Intent intent = new Intent();
                        intent.putExtra("id",0);
                        intent.putExtra("category",category);
                        intent.setClass(getContext(), MoveActivity.class);

                        startActivityForResult(intent, ADD_UPDATE_CODE);
                    }
                });
        singleChoiceDialog.show();
    }
    private void modifyCategory(){
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( uvm.getUser().getCategory_list() );
        intent.putExtra("category_list", kvl  );
        intent.setClass(getContext(), FilterCategory.class);
        startActivityForResult(intent ,COMPLETE_CATEGORY_CODE);
    }

    public  void CompleteAccount(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.setClass(getContext(), AccountActivity.class);
        startActivityForResult(intent, COMPLETE_ACCOUNT_CODE);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        uvm = ViewModelProviders.of(getActivity()).get(UserViewModel.class);
    }

    public  void AddDemand(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }


        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.putExtra("is_new", true);
        intent.setClass(getContext(), DemandNewActivity.class);
        startActivityForResult(intent, ADD_DEMAND_CODE);
    }


    private AsyncTask<Void,Void, GetMyInterestResponse> task = null;
    public void loadData( final Integer thenum ){
//        Integer uid = 0;
//        if (WoyaoooApplication.hasLogin) {
//            uid = userId;
//        }
//        final Integer uuid = uid;

            if (loading) return;
        loading = true;
        if (thenum == 0){
            toploading.setVisibility(View.VISIBLE);
            bottomloading.setVisibility(View.GONE);
        }else{
            toploading.setVisibility(View.GONE);
            bottomloading.setVisibility(View.VISIBLE);
        }


        if (thenum == 0) {
            contentArea.scrollTo(0, 0);

            myInterests.clear();
            nomore = false;
        }

        if(task != null)return;



        task =new AsyncTask<Void, Void, GetMyInterestResponse>() {
            @Override
            protected GetMyInterestResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyInterestResponse> responseCall = svc.getMyInterest(userId,thenum);
                try {
                    GetMyInterestResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyInterestResponse response) {

                if (response.isSuccess()) {
                    renderIt(response);


                }
                if ( !personalAsked && response.getCondition().equals("personal")){
                    personalAsked = true;
                    new AlertDialog.Builder(getContext())
                            .setTitle("信息")
                            .setMessage(response.getMessage())
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    CompleteAccount();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).create().show();

                }

                if ( !demandAsked && response.getCondition().equals("demand")){
                    demandAsked = true;
                    new AlertDialog.Builder(getContext())
                            .setTitle("信息")
                            .setMessage(response.getMessage())
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    AddDemand();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).create().show();

                }


                if ( !contactAsked && response.getCondition().equals("contact")){
                    contactAsked = true;
                    new AlertDialog.Builder(getContext())
                            .setTitle("信息")
                            .setMessage(PERSUASION)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    tryGetContacts();
                                }
                            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).create().show();

                }

                task = null;
                loading = false;
                toploading.setVisibility(View.GONE);
                bottomloading.setVisibility(View.GONE);
            }
            @Override
            protected void onCancelled() {
                loading = false;
                toploading.setVisibility(View.GONE);
                bottomloading.setVisibility(View.GONE);

            }
        };
        task.execute((Void)null);
    }

    private void voteIt(final Integer uid, final String act ,final  InterestSummary interest, final  TextView upCount,final  TextView downCount, final ImageView voteUp,final ImageView voteDown) {
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return ;
        }
        AsyncTask<Void, Void, BaseResponse> task =
                new AsyncTask<Void, Void, BaseResponse>() {

                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);

                        Call<BaseResponse> responseCall = svc.addVote(userId, uid,act);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final BaseResponse response) {
                        if ( response == null ) {
                            Common.showSnack(getContext(), addUpdate,"抱歉,处理失败，请重试。");
                        }else{
                            if (!response.isSuccess()){
                                Common.alert(getContext(),response.getMessage());
                            }else{
                                if (act.equals("up")){
                                    upCount.setText(interest.getPositive() + 1 + "");
                                    voteUp.setImageResource(R.drawable.vote_up_grey);
                                }else {
                                    downCount.setText(interest.getPositive() + 1 + "");
                                    voteDown.setImageResource(R.drawable.vote_down_grey);
                                }


                            }

                        }
                    }

                    @Override
                    protected void onCancelled() {
                        Common.showSnack(getContext(), addUpdate,"抱歉,处理失败，请重试。");
                    }
                };
        task.execute((Void) null);

    }
    private void renderIt(GetMyInterestResponse response){
        if ( myInterests.size() == 0 && response.getContent().size() == 0 )
        {
            emptyArea.setVisibility(View.VISIBLE);
            contentArea.setVisibility(View.GONE);
            return;
        }

        if (myInterests.size()==0){
            theList.removeAllViews();
        }

        emptyArea.setVisibility(View.GONE);
        contentArea.setVisibility(View.VISIBLE);

        if ( response.getContent().size() ==0 && nomore == false){
            LinearLayout item1 = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);
            title1.setText("没有更多了");
            theList.addView(item1);
            nomore = true;
            return;
        }


        //合作的人
        Integer order = myInterests.size();
        for (final InterestSummary interest : response.getContent()) {
            order  = order  + 1;

            LinearLayout whole_item = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.interest_item, null);
            theList.addView(whole_item);
            final TextView interest_order = (TextView) whole_item.findViewById(R.id.interest_order);
            final LinearLayout interest_background = (LinearLayout) whole_item.findViewById(R.id.interest_background);

            final TextView interest_displayname = (TextView) whole_item.findViewById(R.id.interest_displayname);
            final TextView interest_member_title = (TextView) whole_item.findViewById(R.id.interest_member_title);
            final CircleImageView userAvatar = (CircleImageView) whole_item.findViewById(R.id.interest_avatar);
            final TextView move_subject = (TextView) whole_item.findViewById(R.id.move_subject);
            final TextView move_desc = (TextView) whole_item.findViewById(R.id.move_desc);
            final TextView move_created = (TextView) whole_item.findViewById(R.id.move_created);
            final TextView yes_dig_num = (TextView) whole_item.findViewById(R.id.yes_dig_num);
            final TextView no_dig_num = (TextView) whole_item.findViewById(R.id.no_dig_num);
            final LinearLayout mediaItems = (LinearLayout) whole_item.findViewById(R.id.id_move_medias);
            final ImageView voteUp = (ImageView) whole_item.findViewById(R.id.yesdig);
            final ImageView voteDown = (ImageView) whole_item.findViewById(R.id.nodig);
            final LinearLayout moveItem = (LinearLayout) whole_item.findViewById(R.id.moveItem);
            final TextView move_title = (TextView) whole_item.findViewById(R.id.move_title);
            final LinearLayout move_relation_info = (LinearLayout) whole_item.findViewById(R.id.move_relation_info);
            move_title.setText( interest.getTitle());

            move_relation_info.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (interest.getRelation_type().equals("demand")) {
                        Intent intent = new Intent();
                        intent.putExtra("id", interest.getRelation_id());
                        intent.setClass(getContext(), ChanceViewActivity.class);
                        startActivity(intent);
                    }

                    if (interest.getRelation_type().equals("org")) {
                        Intent intent = new Intent();
                        intent.putExtra("id", interest.getRelation_id());
                        intent.setClass(getContext(), OrgViewActivity.class);
                        startActivity(intent);
                    }

                    if (interest.getRelation_type().equals("person")) {
                        Intent intent = new Intent();
                        intent.putExtra("id", interest.getUser_id());
                        intent.setClass(getContext(), PersonViewActivity.class);
                        startActivity(intent);
                    }
                }
            });

            interest_order.setText( order +"");
            interest_background.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (interest.getDemand_id() > 0){
                        Intent intent = new Intent();
                        intent.putExtra("id", interest.getDemand_id());
                        intent.setClass(getContext(), ChanceViewActivity.class);
                        startActivity(intent);
                    }else {
                        Intent intent = new Intent();
                        intent.putExtra("id", interest.getUser_id());
                        intent.setClass(getContext(), PersonViewActivity.class);
                        startActivity(intent);
                    }
                }
            });



            interest_displayname.setText( interest.getDisplayname());
            interest_member_title.setText( interest.getMember_title());


            if (StringUtil.notNullOrEmpty(interest.getSnailview())) {
                Picasso.with(getContext())
                        .load(interest.getSnailview())
                        .into(userAvatar);
            } else {
                userAvatar.setImageResource(R.drawable.no_avartar);
            }


            voteUp.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    voteIt( interest.getId(), "up", interest, yes_dig_num,no_dig_num,voteUp,voteDown);

                }
            });

            voteDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    voteIt( interest.getId(), "down", interest, yes_dig_num,no_dig_num,voteUp,voteDown);
                }
            });

            if  (interest.getVoted()){
                voteUp.setImageResource(R.drawable.vote_up_grey);
                voteDown.setImageResource(R.drawable.vote_down_grey);
            }

            move_desc.setText(interest.getDescription());
            move_created.setText(interest.getCreated());
            if (interest.getPositive() > 0) {
                yes_dig_num.setText(interest.getPositive() + "");
            }else{
                yes_dig_num.setText( "");
            }

            if ( interest.getNegative() >0 ){
                no_dig_num.setText(interest.getNegative() +"");
            }else{
                no_dig_num.setText( "");
            }

            String tempstr = "";
            for (String onestr : interest.getSubject()){
                tempstr += "#" + onestr +" ";
            }
            move_subject.setText( tempstr ) ;

            for (final MediaSummary ms : interest.getMedias()) {
                android.support.v7.widget.ContentFrameLayout image_item = (android.support.v7.widget.ContentFrameLayout) LayoutInflater.from(getContext()).inflate(R.layout.media_item, null);
                ImageView imageView = (ImageView) image_item.findViewById(R.id.media_pic);
                final Button deleteBtn = (Button)image_item.findViewById(R.id.media_delete);
                final Button playBtn = (Button)image_item.findViewById(R.id.media_play);

                image_item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.setClass(getContext(), WebviewActivity.class);
                        intent.putExtra("title", "图片");
                        intent.putExtra("link", ms.getUrl());
                        startActivity(intent);
                    }
                });

                if (ms.getId().endsWith("mp4")){
                    playBtn.setVisibility(View.VISIBLE);
                }else{
                    playBtn.setVisibility(View.GONE);
                }

                deleteBtn.setVisibility(View.GONE);

                if (StringUtil.notNullOrEmpty(ms.getSnailview())) {
                    Picasso.with(getContext())
                            .load(ms.getSnailview())
                            .into(imageView);
                } else {
                    imageView.setImageResource(R.drawable.no_avartar);
                }

                mediaItems.addView(image_item);

            }



            View splitter = (View) LayoutInflater.from(getContext()).inflate(R.layout.splitter, null);
            theList.addView(splitter);
//                if (order < chance.getAgreements().size()) {
//                    View splitter = (View) LayoutInflater.from(ChanceViewActivity.this).inflate(R.layout.light_splitter, null);
//                    agreementsInfo.addView(splitter);
//                }
        }


//            LinearLayout item1 = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.summary_item, null);
//            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);
//
//            title1.setText(chance.getMoves_summary());a
//            theList.addView(item1);
        myInterests.addAll(  response.getContent() ) ;
        toolbar.setTitle( "关注" );
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {

            case ASKCONTACTS_CODE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getContacts();
                } else {
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
                // other 'case' lines to check for other
                // permissions this app might request
            }
        }
    }

    public  void tryGetContacts() {



        if (ContextCompat.checkSelfPermission(getContext(),android.Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(
                    new String[]{android.Manifest.permission.READ_CONTACTS},
                    ASKCONTACTS_CODE);
            Log.i("woyaooo","'授权了吗？'");
        }else{
            getContacts();
        }


    }

    private void getContacts() {

        ArrayList<ContactSummary> contacts = new ArrayList<ContactSummary>();
        ArrayList<String> dups = new ArrayList<String>();
        try {

            cr = getContext().getContentResolver();
//            Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            Cursor cs = null;

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                cs = cr.query(uri, null, null, null,  "sort_key", null);
                StringBuilder sb = new StringBuilder();
                while (cs.moveToNext()) {
                    try {
                        //拿到联系人id 跟name
                        int id = cs.getInt(cs.getColumnIndex("_id"));

                        String number = cs.getString(cs.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        number = number.replace(" ","").replace("+86","");

                        if (dups.contains( number ) ){
                            continue;
                        }
                        dups.add(number);
                        String name = cs.getString(cs.getColumnIndex("display_name"));



                        ContactSummary one = new ContactSummary();
                        one.setId(number);
                        one.setTitle(name  );
                        one.setDescription(number);
                        if (!one.getId().equals("") && !one.getTitle().equals("") && one.getId().length() == 11 && one.getId().startsWith("1") ){
                            contacts.add( one);
                        }

                        sb.append("displayname:" + name + ";");
                        sb.append("phone:" + number + ";");
                        sb.append("#");

                    }catch (Exception e){
                        Log.i("woyaooo", e.getMessage());
                    }
                }
                saveReload( sb.toString()) ;
//                Common.setProfileAttr("contacts", sb.toString());

            }

        }catch (Exception e){
            Toast.makeText(getContext(),"不能访问通讯录", Toast.LENGTH_SHORT).show();
        }
    }


    public   void saveReload( final String content){
        progressDialog = new ProgressDialog(getContext());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在加载······");
        progressDialog.show();
        AsyncTask<Void, Void, Boolean> task = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected Boolean doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.setProfileAttr(userId,"contacts",content);
                Boolean ret = true ;
                try {
                    BaseResponse response = responseCall.execute().body();
                    ret= response.isSuccess();
                } catch (IOException e) {
                    e.printStackTrace();
                    ret = false;
                }
                return ret;
            }

            @Override
            protected void onPostExecute(final Boolean success) {
                progressDialog.dismiss();
                if (success) {
                    loadData(0);


                } else {

                }
            }

            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void) null);

    }
    @Override
    public void onResume() {
        loadUserBasic();
        super.onResume();

    }

    private void loadUserBasic(){
        Application application = getActivity().getApplication();
        SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);

            try {
                WoyaoooApplication.hasLogin = shared.getBoolean("logged", false);
                WoyaoooApplication.userId = shared.getInt("userId", 0);
                WoyaoooApplication.displayname = shared.getString("displayname", "");;
                WoyaoooApplication.location = shared.getString("location", "");
                WoyaoooApplication.title = shared.getString("title", "");
                WoyaoooApplication.snailview = shared.getString("snailview", "");
                WoyaoooApplication.demand_id = shared.getInt("demand_id", 0);
                WoyaoooApplication.member_id = shared.getInt("member_id", 0);
                WoyaoooApplication.message_num = shared.getInt("message_num", 0);

            }catch (Exception e){

            }

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onInterestFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnInterestFragmentInteractionListener) {
            mListener = (OnInterestFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public void loadProfile() {

        final String version = Common.getCurrentVersion(getContext());

        AsyncTask<Void, Void, ProfileResponse> loadTask =
                new AsyncTask<Void, Void, ProfileResponse>() {
                    @Override
                    protected ProfileResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<ProfileResponse> responseCall = svc.getProfile(userId, "android",version);
                        try {
                            ProfileResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ProfileResponse response) {
                        if (response != null && response.isSuccess()) {
                            User user = response.getContent();
                            uvm.initUser( user);

                            Application application = getActivity().getApplication();
                            SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);
                            SharedPreferences.Editor editor = shared.edit();
                            editor.putInt("demand_id", user.getDemand_id());
                            editor.putString("displayname", user.getDisplayname());
                            editor.putString("snailview", user.getSnailview());
                            editor.putString("location", user.getLocation());
                            editor.putString("title", user.getTitle());
                            editor.putString("business", user.getBusiness());
                            editor.putString("business_name", user.getBusiness_name());
                            editor.putInt("member_id", user.getMember_id());
                            editor.putString("mobile", user.getMobile());
                            editor.putString("key", user.getKey());
                            editor.commit();
                            WoyaoooApplication.key = user.getKey();
                            WoyaoooApplication.snailview = user.getSnailview();
                            WoyaoooApplication.displayname = user.getDisplayname();
                            WoyaoooApplication.location = user.getLocation();
                            WoyaoooApplication.title = user.getTitle();
                            WoyaoooApplication.member_id = user.getMember_id();
                            WoyaoooApplication.demand_id = user.getDemand_id();


                            mListener.onMessage(user.getChance_num(), "chance" );
                            mListener.onMessage(user.getMessage_num(), "talk" );
                            mListener.onMessage(user.getCooperate_num(), "cooperate" );
                            mListener.onMessage(user.getPerson_num(), "person" );
                            mListener.onMessage(user.getInterest_num(), "interest" );

                        }
                    }
                };
        loadTask.execute((Void) null);
    }


    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnInterestFragmentInteractionListener {
        // TODO: Update argument type and name
        void onInterestFragmentInteraction(Uri uri);
        void onMessage(Integer messageNum, String info);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == ADD_UPDATE_CODE && resultCode == 666 ) {

                loadData(0);
        }

        if  (requestCode == MYREGISTER_CODE && resultCode == 666 ){
            loadProfile();
            loadData(0);

        }

        if  (requestCode == COMPLETE_CATEGORY_CODE && resultCode ==666 ){
//            String categoryNo = data.getStringExtra("category");
//            String categoryName = data.getStringExtra("category_name");
//
//            uvm.getUser().setCategory(categoryNo);
//            uvm.getUser().setCategory_name( categoryName);
//            changeProfile("category", categoryNo);


            KeyValueList thelist = (KeyValueList) data.getExtras().get("result");
            String nos = Common.KeyValueToNos(thelist.getContent());
            String names = Common.KeyValueToNames(thelist.getContent());
            uvm.getUser().setCategory(nos);
            uvm.getUser().setCategory_name( names);

            loadData(0);

        }
    }
}
